// createRouter          用于创建路由的函数
// createWebHashHistory  用于创建哈希路由的函数
import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '@/views/Layout.vue'
import Home from '@/views/home/index.vue'
import CategoryIndex from '@/views/category/index.vue'
import CategorySub from '@/views/category/sub.vue'
import GoodsDetail from '@/views/goods/index.vue'
import Login from '@/views/login/index.vue'
import LoginCallBack from '@/views/login/callback.vue'
import Cart from '@/views/cart/index.vue'
import Checkout from '@/views/member/pay/checkout.vue'
import Pay from '@/views/member/pay/index.vue'
import PayCallBack from '@/views/member/pay/callback.vue'
import MemberLayout from '@/views/member/Layout.vue'
import MemberHome from '@/views/member/home/index.vue'
import MemberOrder from '@/views/member/order/index.vue'
import MemberOrderDetail from '@/views/member/order/detail.vue'

import store from '@/store'
import { h } from 'vue'
// 配置路由，，路径和组件的映射关系
const routes = [
  {
    // Layout布局组件(公共头部和底部)
    path: '/',
    component: Layout,
    // 需要用到公共 Layout 的页面
    children: [
      { path: '', component: Home }, // 首页组件
      { path: 'category/:id', component: CategoryIndex }, // 一级分类页
      { path: 'category/sub/:id', component: CategorySub }, // 二级分类页
      { path: 'product/:id', component: GoodsDetail }, // 二级分类页
      { path: 'cart', component: Cart },
      { path: 'member/checkout', component: Checkout },
      { path: 'member/pay', component: Pay },
      { path: 'member/pay/callback', component: PayCallBack },
      {
        path: 'member',
        component: MemberLayout,
        children: [
          { path: '', component: MemberHome },
          // { path: 'order', component: MemberOrder },
          // { path: 'order/:id', component: MemberOrderDetail }
          {
            path: 'order',
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }
            ]
          }
        ]
      }
    ]
  },
  { path: '/login', component: Login },
  { path: '/login/callback', component: LoginCallBack }
]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 路由进阶 - 滚动行为
  scrollBehavior (to, from, savedPosition) {
    // console.log(to.path)
    // console.log(savedPosition)
    if (to.path !== '/') {
      // 始终滚动到顶部，behavior: 'smooth' 平滑滚动效果
      return { top: 0, behavior: 'smooth' }
      // Vue2返回的是 { x:0 , y:0 }
      // Vue3返回的是 { left:0 , top:0 }
    } else {
      return savedPosition
    }
  }
})

// 路由前置导航守卫
router.beforeEach((to, from) => {
  // 跳转去member开头的地址，却没有登录
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    // 跳转到登录页，并传递
    // return '/login?redirectUrl=' + to.fullPath
    return { path: '/login', query: { redirectUrl: to.fullPath } }
  }
})

// 导出路由实例
export default router
